<script setup>
import { reactive, ref } from "vue";
import { onMounted } from "vue";
import {
  selectAllUser,
  deleteUser,
  getClassInfo,
  updateUserClass,
  findAllClassroom
} from "@/api/common/work/CourseUp";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRoute } from "vue-router";
import { useTokenStore } from "@/store/token.js";
const token = useTokenStore();
const classOptions = ref([]); // 班级下拉选项
const selectedClassId = ref(null); // 选中的班级ID
const currentUserId = ref(null); // 当前操作的用户ID
const dialogVisible = ref(false); // 弹出层显示状态
// 方法：获取班级列表
const fetchClassOptions = async () => {
  try {
    const res = await findAllClassroom();
    console.log(res.data);
    classOptions.value = res.data || []; // 确保有数据
  } catch (error) {
    console.error('获取班级列表失败', error);
    ElMessage.error('获取班级列表失败');
  }
};

// 方法：打开转班弹出层
const handleTransferClass = (userId) => {
  currentUserId.value = userId; // 保存当前用户ID
  dialogVisible.value = true; // 显示弹出层
  console.log('dialogVisible:', dialogVisible.value); // 检查是否成功修改
};

// 方法：提交转班
const submitTransfer = async () => {
  if (!selectedClassId.value) {
    ElMessage.warning('请选择班级');
    return;
  }
  try {
    console.log(currentUserId.value);
    console.log(selectedClassId.value);
    await updateUserClass(currentUserId.value, selectedClassId.value);
    ElMessage.success('转班成功');
    dialogVisible.value = false; // 关闭弹出层
  } catch (error) {
    console.error('转班失败', error);
    ElMessage.error('转班失败，请稍后重试');
  }
};
const route = useRoute();
import { get } from "jquery";
// 屏幕宽度
const windowWidth = ref(0);
// 屏幕高度
const windowHeight = ref(0);
const classId = ref(0);
const classInfo = ref({});
// 生命周期
onMounted(() => {
  fetchClassOptions();
  getWindowResize();
  window.addEventListener("resize", getWindowResize);
  // console.log(route.query.classId)
  classId.value = route.query.classId;
  getClass();
  getAllUser();
  let table= findAllClassroom();
  console.log(table)
});
const getClass = async () => {
  let res = await getClassInfo(classId.value);
  classInfo.value = res.data;
};
const updateUserClassHandler = async (userId) => {
  console.log(userId);
 // await updateUserClass(userId, classId);
};

// 获取屏幕尺寸
const getWindowResize = function () {
  windowWidth.value = window.innerWidth;
  windowHeight.value = window.innerHeight;
};
const handleClick = () => {
  console.log("click");
};
const getAllUser = async () => {
  let res = await selectAllUser(classId.value);
  if (res.data != "" || res.data != null || res.data.length != 0) {
    res.data.forEach((element) => {
      if (element.userSex == 0) {
        element.userSex = "男";
      } else {
        element.userSex = "女";
      }
      tableData.push(element);
    });
  }
};

const tableData = reactive([]);

function showFileChooser() {
  const input = document.createElement("input");
  input.type = "file";
  input.accept =
    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
  input.click();
  input.addEventListener("change", async function () {
    const file = this.files[0];
    if (!file) return;
    const formData = new FormData();
    formData.append("file", file);
    formData.append("classId", classId.value);
    const xhr = new XMLHttpRequest();
    xhr.open("POST", "/api/excel/importData", true); // 假设你的后端API位于"/upload"
    xhr.setRequestHeader("Authorization", token.token);
    // 设置进度条更新函数
    xhr.upload.addEventListener("progress", function (event) {});
    xhr.onload = function () {
      if (xhr.status === 200) {
        console.log("File uploaded successfully.");
        const response = JSON.parse(xhr.responseText);
        console.log(response);
        if (response.code == 333) {
          ElMessage({
            type: "warning",
            message: response.msg,
          });
        }
        setTimeout(() => {
          location.reload();
        }, 2000);
      } else {
        console.error("Error uploading file.");
      }
    };
    xhr.send(formData);
  });
}

const open = (userId) => {
  ElMessageBox.confirm("是否将该学生移除当前班级并删除学生", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "返回",
    type: "warning",
  })
    .then(async () => {
      await deleteUser(userId);
      location.reload();
      ElMessage({
        type: "success",
        message: "移除成功",
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "放弃移除",
      });
    });
};
//清空学生
const qk = async () =>{
    ElMessageBox.confirm("是否将全部学生移除当前班级并删除学生", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "返回",
    type: "warning",
  })
    .then(async () => {
      await qk01();
      location.reload();
      ElMessage({
        type: "success",
        message: "移除成功",
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "放弃移除",
      });
    });
}
const qk01 =() =>{
  console.log(tableData)
    tableData.forEach((aa)=>{
      deleteUser(aa.userId);
  })
}
</script>
<template>
  <div class="resourceTop">
    <div class="top">
      <div class="logo">
        <img src="../../../assets/img/kechengziyuan.png" alt="" />
      </div>
      <div class="text">
        <p class="title">{{ classInfo.className }}</p>
        <p>
          <span
            >创建者：{{ classInfo.nickName }} &nbsp;&nbsp;&nbsp;学员数量：{{
              tableData.length
            }}</span
          >
        </p>
      </div>
      <div class="add">
        <button @click="showFileChooser()">批量导入学员信息</button>
        <a
          href="https://prcpic.oss-cn-beijing.aliyuncs.com/%E5%AD%A6%E5%91%98%E4%BF%A1%E6%81%AF%E8%A1%A8%28%E6%A8%A1%E6%9D%BF%29.xlsx"
          title="点击下载学生信息模板"
        >
          <button
            style="
              width: 150px;
              height: 40px;
              background-color: #f4523b;
              border: none;
              color: #fff;
              font-size: 16px;
              border-radius: 5px;
              cursor: pointer;
              margin-left: 20px;
            "
          >
            下载学生信息模板
          </button>
        </a>
      </div>
        <el-button class="qk" type="success" round @click="qk"> 清空学生</el-button>
    </div>
  </div>
  <div
    class="bottom"
    :style="{
      height: windowHeight - 180 + 'px',
      width: windowWidth - 80 + 'px',
    }"
  >
    <el-table :data="tableData" style="width: 94%; margin: 0 auto">
      <el-checkbox-group v-model="checkList">
        <el-checkbox
          label="Option A"
          :value="tableData.userId"
          style="border: 1px solid red"
        />
      </el-checkbox-group>
      <el-table-column fixed prop="nickName" label="名字" width="150" />
      <el-table-column prop="userName" label="账号" width="200" />

      <el-table-column prop="userEmail" label="邮箱" width="240" />
      <el-table-column prop="userCard" label="身份证" width="250" />
      <el-table-column prop="userSex" label="性别" width="200" />
      <el-table-column prop="userPhone" label="手机号" width="200" />
      <el-table-column fixed="right" label="操作" min-width="120">
        <template #default="tableData">
          <el-button
            link
            type="primary"
            size="small"
            @click="open(tableData.row.userId)"
            >删除</el-button
          >
          <el-button
            link
            type="primary"
            size="small"
            @click="handleTransferClass(tableData.row.userId)"
          >
            转班
          </el-button>
        </template>
      </el-table-column>
    </el-table>
     <!-- 弹出层 -->
     <el-dialog
  v-model="dialogVisible"
  title="转班"
  width="30%"
  :close-on-click-modal="false"
>
  <p>请输入转到的班级</p>
  <el-select v-model="selectedClassId" placeholder="请选择班级">
    <el-option
      v-for="option in classOptions"
      :key="option.classId"
      :label="option.className"
      :value="option.classId"
    />
  </el-select>
  <template #footer>
    <el-button @click="dialogVisible = false">取消</el-button>
    <el-button type="primary" @click="submitTransfer">确定</el-button>
  </template>
</el-dialog>

  </div>
</template>
<style scoped>
.top{
  
  position: relative;
}
.qk{
  position: relative;
  right: 80px;
  top: 50px;
  width: 80px;
  height: 30px;
}
.bottom {
  background-color: #f8f8f8;
}

.resourceTop {
  width: 100%;
  height: 120px;
  background-color: #f5f5f5;
}

.resourceTop .top {
  width: 100%;
  height: 100px;
  display: flex;
  align-items: center;
  justify-items: center;
}

.resourceTop .top .logo {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  margin-left: 45px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #ff6b0f;
}

.resourceTop .top .logo img {
  width: 30px;
  height: 30px;
  padding: 12px;
  cursor: pointer;
}

.resourceTop .top .text {
  width: 350px;
  height: 100px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  margin-left: 20px;
}

.resourceTop .top .text .title {
  font-size: 22px;
  font-weight: 500;
  color: rgba(0, 0, 0, 0.85);
  margin-bottom: 10px;
}

.resourceTop .top .text p span {
  color: rgba(0, 0, 0, 0.45);
}

.resourceTop .top .text p a {
  color: #f4523b;
}

.resourceTop .top .add {
  margin-left: 550px;
}

.resourceTop .top .add button {
  width: 150px;
  height: 40px;
  background-color: #f4523b;
  border: none;
  color: #fff;
  font-size: 16px;
  border-radius: 5px;
  cursor: pointer;
}

.resourceTop .top .select {
  margin-left: 10px;
  display: flex;
}

.resourceTop .top .select select {
  width: 100px;
  height: 40px;
  margin-right: 10px;
  font-size: 16px;
  padding-left: 20px;
  border: 1px solid #d6d6d6;
  border-radius: 5px;
}

.resourceTop .top .select select option {
  color: #676767;
  cursor: pointer;
}

.resourceTop .top .select button {
  width: 100px;
  height: 40px;
  border: 1px solid #d6d6d6;
  border-radius: 5px;
  cursor: pointer;
  font-size: 16px;
  background-color: #fff;
}

.resourceTop .top .select button:hover {
  background-color: #f9e3e3;
}

.resourceTop .top .select select:hover {
  color: #f4523b;
  cursor: pointer;
}

.resourceTop .top .select select:focus {
  border: 1px solid #d6d6d6;
  outline: none;
}

.resourceTop .top .search {
  margin-left: 15px;
  display: flex;
  border-radius: 2px;
  background-color: #fafafa;
  justify-items: center;
  align-items: center;

  border: 1px solid #d6d6d6;
}

.resourceTop .top .search:hover {
  border: 1px solid #f4523b;
}

.resourceTop .top .search .sousuo {
  width: 40px;
  height: 40px;
  padding-left: 5px;
  padding-top: 5px;
  border-right: none;
  background-color: #fff;
}

.resourceTop .top .search .sousuo img {
  width: 80%;
}

.resourceTop .top .search input {
  width: 320px;
  height: 40px;
  border: none;
  background-color: #fff;
  border-left: none;
}

.resourceTop .top .search input:focus {
  outline: none;
}

.resourceTop .top .search:hover .sousuo {
  border-right: none;
}

.resourceTop .top .search:hover input {
  border-left: none;
}

.resourceTop .bottom {
  display: flex;
  height: 50px;
}

.resourceTop .bottom .text {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 150px;
  height: 50px;
  font-size: 20px;
  margin-left: 10px;
  border: none;
  cursor: pointer;
}
</style>
